package com.yanti.config;

import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
import org.springframework.core.convert.converter.Converter;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Configuration
public class MongoConfig {

    @Bean
    public MongoCustomConversions customConversions() {
        List<Converter<?, ?>> converters = new ArrayList<>();

        // LocalDateTime -> Date
        converters.add(new Converter<LocalDateTime, Date>() {
            @Override
            public Date convert(@NotNull LocalDateTime source) {
                return Date.from(source.atZone(ZoneId.systemDefault()).toInstant());
            }
        });

        // Date -> LocalDateTime
        converters.add(new Converter<Date, LocalDateTime>() {
            @Override
            public LocalDateTime convert(@NotNull Date source) {
                return source.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
            }
        });

        return new MongoCustomConversions(converters);
    }
}
